#!/usr/bin/env python
#coding:utf-8
"""
  Author:  程勇 --<>
  Purpose: 动脑学院19节作业
  Created: 2018/3/11
"""

import os
import time 
from multiprocessing import Process,cpu_count,Pool
from threading import Thread
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from multiprocessing.dummy import Pool as ThreadPool

'''
主要是练习装饰器,和多线程,多进程的使用
使用装饰器增强完成1-999999所有奇数和计算10次
'''

#统计运行时间
def run_time(func):
    def record():
        start_time = time.time()
        func()
        end_time = time.time()
        
        print('运行时间为:{}'.format(end_time - start_time))
    
    return record

#1-999999所有奇数相加
def sum_even():
    return sum(range(1,1000000,2))

#1.使用普通方法
@run_time
def normal():
    for i in range(1,11):
        sum_even()
        
#3.使用多进程
@run_time
def pro():
    process_list = [Process(target=sum_even,args=()) for i in range(1,11)]
    
    for p in process_list:
        p.start()
        
    for p_s in process_list:
        p.join()

#2.使用多线程
@run_time
def thr():
    thread_list = [Thread(target=sum_even,args=()) for i in range(1,11)]
    
    for t in thread_list:
        t.start()
        
    for t in thread_list:
        t.join()
        
# 4.采用线程池完成计算
@run_time
def thread_pool():
    with ThreadPoolExecutor(max_workers=cpu_count()) as executor:
        future_sum = [executor.submit(sum_even) for i in range(1,11)]

@run_time
def thread_pool_second():
    pool = ThreadPool(cpu_count())
    for i in range(1,11):
        pool.apply_async(sum_even,args=())
    pool.close()
    pool.join()    
    
#5.采用进程池完成计算
@run_time
def process_pool():
    with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
        future_sum = [executor.submit(sum_even) for i in range(1,11)]

@run_time
def process_pool_second():
    pool = Pool(cpu_count())
    for i in range(1,11):
        pool.apply_async(sum_even,args=())
    pool.close()
    pool.join()    
        
if __name__ == '__main__':
    
    print('1.使用普通方法')
    normal()
    
    print('2.使用多线程')
    thr()
    
    print('3.使用多进程')
    pro()
    
    print('4.使用线程池')
    thread_pool()
    thread_pool_second()
    
    print('4.使用进程池')
    process_pool()
    process_pool_second()

